﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PersonalFinanceManager.Repositories.Repositories;
using System.Drawing;
using System.Linq.Expressions;
using System.Data.Objects.SqlClient;

namespace PersonalFinanceManager.Website
{
    public partial class BillsTransactionTypes : System.Web.UI.Page
    {
        BillsTransactionsRepository billsTransactionsRepo = new BillsTransactionsRepository();
        int sessionUserID;

        protected void Page_Load(object sender, EventArgs e)
        {
            sessionUserID = 1; // Convert.ToInt32(Session["UserID"]);

            if (!IsPostBack)
            {
                ResetForm(true, "");
                txtSearchDateFrom.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date.AddMonths(-1));
                txtSearchDateTo.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date);

                for (int i = 0; i <= 23; i++)
                {
                    string s = String.Format("{0:00}", i);
                    ddlHour.Items.Add(new ListItem(s, s));
                }
                for (int i = 0; i < 60; i += 15)
                {
                    string s = String.Format("{0:00}", i);
                    ddlMinute.Items.Add(new ListItem(s, s));
                }
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IList<DataModel.BillsTransactions> billsTransactions;
            DateTime searchDateFrom = Convert.ToDateTime(txtSearchDateFrom.Text).Date;
            DateTime searchDateTo = Convert.ToDateTime(txtSearchDateTo.Text).Add(new TimeSpan(23, 59, 59));

            string s = txtSearch.Text;
            Expression<Func<DataModel.BillsTransactions, bool>> whereCondition = (x => (x.Name.Contains(s) || x.Description.Contains(s))
                                                                            && (x.DateOfBillsTransaction >= searchDateFrom && x.DateOfBillsTransaction <= searchDateTo)
                                                                             );
            billsTransactions = billsTransactionsRepo.FindAll(whereCondition, (x => x.DateOfBillsTransaction), Repositories.SortingMode.descending);

            gvBillsTransactions.DataSource = billsTransactions;
            gvBillsTransactions.DataBind();


            lblTotalCount.Text = billsTransactions.Count.ToString();
            lblTotalDateFrom.Text = String.Format("{0:dd.MM.yyyy}", searchDateFrom);
            lblTotalDateTo.Text = String.Format("{0:dd.MM.yyyy}", searchDateTo);
            lblTotalMoney.Text = String.Format("{0:0.00} ден.", billsTransactions.Sum(x => x.Money));

            txtName.Focus();
        }

        protected void gvBillsTransactions_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = Convert.ToInt32(e.Keys["ID"]);
            DataModel.BillsTransactions billsTransaction = new DataModel.BillsTransactions();
            billsTransaction.ID = id;

            billsTransactionsRepo.Delete(billsTransaction);
        }

        protected void gvBillsTransactions_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(gvBillsTransactions.DataKeys[gvBillsTransactions.SelectedIndex]["ID"]);
            DataModel.BillsTransactions billsTransaction = billsTransactionsRepo.GetSingle(x => x.ID == id);
            ViewState["ID"] = billsTransaction.ID;

            txtName.Text = billsTransaction.Name;
            txtMoney.Text = String.Format("{0:0}", Math.Round(billsTransaction.Money));
            txtDateOfBillsTransaction.Text = String.Format("{0:dd.MM.yyyy}", billsTransaction.DateOfBillsTransaction.Date);
            ddlHour.SelectedValue = String.Format("{0:00}", billsTransaction.DateOfBillsTransaction.Hour);
            ddlMinute.SelectedValue = String.Format("{0:00}", billsTransaction.DateOfBillsTransaction.Minute);
            txtDescription.Text = billsTransaction.Description;

            ResetForm(false, billsTransaction.Name);
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            DataModel.BillsTransactions billsTransaction = new DataModel.BillsTransactions();
            billsTransaction.UserID = sessionUserID;
            billsTransaction.Name = txtName.Text;
            billsTransaction.Money = Convert.ToDecimal(txtMoney.Text);
            billsTransaction.DateOfBillsTransaction = Convert.ToDateTime(txtDateOfBillsTransaction.Text).AddHours(Convert.ToInt32(ddlHour.SelectedValue)).AddMinutes(Convert.ToInt32(ddlMinute.SelectedValue));
            billsTransaction.Description = txtDescription.Text;
            
            billsTransactionsRepo.Insert(billsTransaction);

            ResetForm(true, "");
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(ViewState["ID"]);
            DataModel.BillsTransactions billsTransaction = billsTransactionsRepo.GetSingle(x => x.ID == id);
            billsTransaction.Name = txtName.Text;
            billsTransaction.Money = Convert.ToDecimal(txtMoney.Text);
            billsTransaction.DateOfBillsTransaction = Convert.ToDateTime(txtDateOfBillsTransaction.Text).AddHours(Convert.ToInt32(ddlHour.SelectedValue)).AddMinutes(Convert.ToInt32(ddlMinute.SelectedValue));
            billsTransaction.Description = txtDescription.Text;

            billsTransactionsRepo.Update(billsTransaction);

            ResetForm(true, "");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ResetForm(true, "");
        }

        protected void ResetForm(bool isInsert, string billsTransactionname)
        {
            if (isInsert)
            {
                foreach (Control c in pnlBillsTransactions.Controls)
                    if (c is TextBox)
                        (c as TextBox).Text = "";

                btnInsert.Visible = true;
                btnUpdate.Visible = false;
                pnlBillsTransactions.GroupingText = "Внеси уплатена сметка";
                pnlBillsTransactions.DefaultButton = "btnInsert";
                txtDateOfBillsTransaction.Text = String.Format("{0:dd.MM.yyyy}", DateTime.Now.Date);
            }
            else
            {
                btnInsert.Visible = false;
                btnUpdate.Visible = true;
                pnlBillsTransactions.GroupingText = "Промени сметка " + billsTransactionname;
                pnlBillsTransactions.DefaultButton = "btnUpdate";
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
        }

        protected void btnResetSearch_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
        }
    }
}